<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Think\Exception;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController
{

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index()
    {
        $nickname = I('nickname');
        $map['status'] = array('egt', 0);
        if (is_numeric($nickname)) {
            $map['uid|nickname'] = array(intval($nickname), array('like', '%' . $nickname . '%'), '_multi' => true);
        } else {
            $map['nickname'] = array('like', '%' . (string)$nickname . '%');
        }

        $list = $this->lists('Member', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '教师信息';
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname()
    {
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display('updatenickname');
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname()
    {
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User = new UserApi();
        $uid = $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member = D('Member');
        $data = $Member->create(array('nickname' => $nickname));
        if (!$data) {
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid' => $uid))->save($data);

        if ($res) {
            $user = session('user_auth');
            $user['username'] = $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        } else {
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword()
    {
        $this->meta_title = '修改密码';
        $this->display('updatepassword');
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword()
    {
        //获取参数
        $password = I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if ($data['password'] !== $repassword) {
            $this->error('您输入的新密码与确认密码不一致');
        }
        $data['update_pass'] = 1;
        $Api = new UserApi();
        $res = $Api->updateInfo(UID, $password, $data);
        if ($res['status']) {
            $this->success('修改密码成功！');
        } else {
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action()
    {
        //获取列表数据
        $Action = M('Action')->where(array('status' => array('gt', -1)));
        $list = $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction()
    {
        $this->meta_title = '新增行为';
        $this->assign('data', null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction()
    {
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data', $data);
        $this->meta_title = '编辑行为';
        $this->display('editaction');
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction()
    {
        $res = D('Action')->update();
        if (!$res) {
            $this->error(D('Action')->getError());
        } else {
            $this->success($res['id'] ? '更新成功！' : '新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method = null)
    {
        $id = array_unique((array)I('id', 0));
        if (in_array(C('USER_ADMINISTRATOR'), $id)) {
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] = array('in', $id);
        switch (strtolower($method)) {
            case 'forbiduser':
                $this->forbid('Member', $map);
                break;
            case 'resumeuser':
                $this->resume('Member', $map);
                break;
            case 'deleteuser':
                $this->delete('Member', $map);
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $password = '', $repassword = '', $email = '')
    {
        if (IS_POST) {
            /* 检测密码 */
            if ($password != $repassword) {
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User = new UserApi;
            $uid = $User->register($username, $password, $email);
            if (0 < $uid) { //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                if (!M('Member')->add($user)) {
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！', U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->meta_title = '新增用户';
            $this->display();
        }
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0)
    {
        switch ($code) {
            case -1:
                $error = '用户名长度必须在16个字符以内！';
                break;
            case -2:
                $error = '用户名被禁止注册！';
                break;
            case -3:
                $error = '用户名被占用！';
                break;
            case -4:
                $error = '密码长度必须在6-30个字符之间！';
                break;
            case -5:
                $error = '邮箱格式不正确！';
                break;
            case -6:
                $error = '邮箱长度必须在1-32个字符之间！';
                break;
            case -7:
                $error = '邮箱被禁止注册！';
                break;
            case -8:
                $error = '邮箱被占用！';
                break;
            case -9:
                $error = '手机格式不正确！';
                break;
            case -10:
                $error = '手机被禁止注册！';
                break;
            case -11:
                $error = '手机号被占用！';
                break;
            default:
                $error = '未知错误';
        }
        return $error;
    }

    /**编辑用户资料
     * @param string $uid 用户id
     */
    public function editUserinfo($uid = '')
    {
        if (IS_POST) {

            $yzm = I('post.yzm');
            unset($_POST['yzm']);
            $_POST['subject_name']=implode(',',$_POST['subject_name']);
            $this->editRow('Member', $_POST, ['uid' => $uid]);
        } else {
            $userinfo = M('Member')->where('uid=%d', UID)->find();
            $s_list=M('subjects')->field("sid,subject_name")->where("status=%d",1)->select();
            $subject_name=explode(',',$userinfo['subject_name']);

            foreach($s_list as &$v){

               if(in_array($v['sid'],$subject_name)){
                   $v['val']=1;
               }
            }
            $this->assign('s_list',$s_list);
            $this->assign('userinfo', $userinfo);
            $this->meta_title = '编辑用户资料';
            $this->display();
        }

    }

    /**
     * 年级信息列表
     */
    public function gradeInformation()
    {
        $result = $this->lists('Grade');
        $this->assign('_list', $result);
        $this->meta_title = '年级信息';
        $this->display();
    }

    /**
     * 新增年级
     */
    public function classAdd()
    {
        if (IS_POST) {
            $arr = D('Grade')->data_into($_POST);
            if ($arr['state'] == 'success') {
                $this->success($arr['info']);
            } else {
                $this->error($arr['info']);
            }
        } else {
            $_list = M('Member')->field("uid,nickname")->where("status=%d", 1)->select();
            $this->assign('_list', $_list);
            $this->meta_title = '新增年级';
            $this->display();
        }

    }

    //年级状态操作
    public function classStatus($method = null)
    {
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map['gid'] = array('in', $id);
        switch (strtolower($method)) {
            case 'forbidclass':
                $this->forbid('Grade', $map);
                break;
            case 'resumeclass':
                $this->resume('Grade', $map);
                break;
            case 'deleteclass':
                $this->delete('Grade', $map);
                break;
            default:
                $this->error('参数非法');
        }
    }

    /**
     * 年级管理
     */
    public function classGuanli()
    {

        $this->meta_title = '年级管理';
        $this->display();
    }

    /**年级成绩管理
     *
     */
    public function performance($gid = '')
    {

        $_list = $this->lists('Examine', is_where(1,'gid',$gid));
        $this->assign('_list', $_list);
        $this->meta_title = '成绩管理';
        $this->display();
    }

    //成绩分析
    public function gradeAnalyze()
    {

        $this->meta_title = '成绩分析';
        $this->display();
    }

    //添加考试
    public function addExamination()
    {
        if (IS_POST) {
            $sub_data = [];//考试科目数据
            $sub_data['subject_name'] = I('post.subject_name');
            $sub_data['difficulty'] = I('post.difficulty');
            $sub_data['pass_nubmer'] = I('post.pass_nubmer');
            $sub = putarry($sub_data, 'subject_name');
            $emax_data = [];//考试数据
            $emax_data['exam_name'] = I('post.exam_name');
            $emax_data['exam_category'] = I('post.exam_category');
            $emax_data['exam_time'] = I('post.exam_time');
            $emax_data['exam_difficulty'] = I('post.exam_difficulty');
            $emax_data['grade_id'] = I('post.grade_id');
            $emax_data['explains'] = I('post.explains');
            $emax_data['gid'] = I('post.gid');
            $emax_data['create_time'] = time();
            $emax_data['uid'] = UID;
            if (!D('Examine')->create()) {
                $this->error(D('Examine')->getError());
                exit;
            }
            $eOb = M('Examine');
            $eOb->startTrans();
            try {
                $eid = $eOb->add($emax_data);
                foreach ($sub as $v) {
                    $v['eid'] = $eid;
                    M('ExamSubject')->add($v);
                }
                $eOb->commit();
                $this->success('提交成功');
            } catch (Exception $e) {
                $eOb->rollback();
                $this->error('提交失败');
            }

        } else {
            $cate_list = M('ExamCate')->where("status=%d", 1)->select();
            $sub_list = M('Subjects')->where("status=%d", 1)->select();
            $this->assign('cate_list', $cate_list);
            $this->assign('sub_list', $sub_list);
            $this->meta_title = '新增考试';
            $this->display();
        }

    }

    //考试设置
    public function examSetting($type_id = '')
    {
        if (IS_POST) {
            $re = putarry($_POST, 'cate_name');
            foreach ($re as $v) {
                if ($v['cid']) {
                    $result = M('ExamCate')->where("cid=%d", $v['cid'])->save(['cate_name' => $v['cate_name']]);
                } else {
                    $result = M('ExamCate')->add(['cate_name' => $v['cate_name'], 'type_id' => $type_id, 'create_time' => time()]);
                }
            }
            if ($result) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $_list1 = M('ExamCate')->where("status=%d and type_id=%d", [1, 1])->select();
            $_list2 = M('ExamCate')->where("status=%d and type_id=%d", [1, 2])->select();
            $this->assign('_list1', $_list1);
            $this->assign('_list2', $_list2);
            $this->meta_title = '考试设置';
            $this->display();
        }

    }

    //删除难以类别
    public function cateDel($cid = '')
    {
        if (IS_AJAX) {
            $this->delete('ExamCate', ['cid' => $cid]);
        }
    }

    //科目设置
    public function subjects()
    {
        $_list = $this->lists('Subjects', ['status' => 1],'sid asc');
        $this->assign('_list', $_list);
        $this->meta_title = '科目设置';
        $this->display();
    }

    //新增科目
    public function addSubject($sid = '')
    {
        if (IS_POST) {
            $_POST['rules'] = join($_POST['rules'], ',');
            if (!empty($sid)) {
                $this->editRow('Subjects', $_POST, ['sid' => $sid]);
            } else {
                $arr = D('Subjects')->adds($_POST);
                if ($arr['state'] == 'error') {
                    $this->error($arr['info']);
                } else {
                    $this->success($arr['info']);
                }
            }


        } else {
            if (!empty($sid)) {
                $info = M('Subjects')->where("sid=%d", $sid)->find();
                $this->assign('info', $info);
            }
            $this->meta_title = '编辑科目';
            $this->display();
        }

    }

    //删除科目
    public function subdel($sid = '')
    {
        if (IS_AJAX) {
            $this->delete('Subjects', ['sid' => $sid]);
        }
    }

    //班级管理
    public function classAndGrade($gid='')
    {

        if(!empty($gid)){
            $where=is_where(1,'gid',$gid);
        }else{
            $where=is_where();
        }
        $_list=$this->lists('ClassGrade',$where);
        $this->assign('_list',$_list);
        $this->meta_title='班级管理';
        $this->display();
    }

    //添加班级
    public function addGrade($gid='')
    {
        if(IS_POST){
            $cObj=D('ClassGrade');
            if(!$cObj->create()){
                $this->error($cObj->getError());
            }else{
                $_POST['create_time']=time();
                if($class_id=$cObj->add($_POST)){
                    $uid=I('post.uid');
                    $class_id .=',';
                    $sql="UPDATE sc_member SET class_id=CONCAT(class_id,'{$class_id}')WHERE uid=$uid";
                    $re=M()->execute($sql);
                    $this->success('操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }else{
            $_list = M('Member')->field("uid,nickname")->where("status=%d", 1)->select();
            if(empty($gid)){
                $grade_data=$this->lists('Grade',['status'=>1]);
                $this->assign('grade_data',$grade_data);
            }
            $this->assign('_list', $_list);
            $this->meta_title = '新增班级';
            $this->display();
        }

    }
    //课程表
    public function syllabus(){

        $this->display();
    }

    //学生信息
    public function studentList(){
        $prefix   = C('DB_PREFIX');
        $l_table=$prefix.'students_info';
        $r_table=$prefix.'class_grade';
        $model    = M()->table( $l_table.' a' )->join ( $r_table.' b ON a.cid=b.id' );
        $_list=$this->lists($model,array('a.status'=>array('egt',0)),'a.stid asc','a.stid,a.username,a.student_number,a.sex,a.idcard,a.update_time,b.grade_name');
        $this->assign('_list',$_list);
        $this->meta_title = '学生信息';
        $this->display();
    }
    //班级学生信息
    public function classStudentList($cid=''){
        $prefix   = C('DB_PREFIX');
        $l_table=$prefix.'students_info';
        $r_table=$prefix.'class_grade';
        $model    = M()->table( $l_table.' a' )->join ( $r_table.' b ON a.cid=b.id' );
        $_list=$this->lists($model,array('a.status'=>array('egt',0),'a.cid'=>$cid),'a.stid asc','a.stid,a.username,a.student_number,a.sex,a.idcard,a.update_time,b.grade_name');
        $man_count=M('StudentsInfo')->where("status >%d and cid=%d and sex=%d",[0,$cid,0])->count();
        $this->assign('man_count',$man_count);
        $this->assign('_list',$_list);
        $this->assign('gid',class_gradeid($cid));
        $this->assign('cid',$cid);
        $this->meta_title = '学生信息';
        $this->display();

    }

    //添加学生
    public function addStudent($stid=''){
        if(IS_POST){
            $_POST['password']=md5($_POST['password']);
            $arr=D('StudentsInfo')->addStudent($stid,$_POST);
            if($arr['state']=='success'){
                $this->success($arr['info']);
            }else{
                $this->error($arr['info']);
            }

        }else{
            if(!empty($stid)){
                $userinfo=M('StudentsInfo')->where("stid=%d",$stid)->find();
                $gid=$userinfo['gid'];
                $class_info=$this->lists('ClassGrade',['gid'=>$gid]);
                $this->assign('class_info',$class_info);
                $this->assign('userinfo',$userinfo);
            }

            $class_list=M('Grade')->field("class_name,gid")->where("status=%d",1)->select();//年级信息
            $this->assign('class_list',$class_list);
            $this->meta_title = '编辑学生信息';
            $this->display();
        }

    }
    //删除学生信息
    public function stdel($stid=''){
        if(IS_AJAX){
            if(M('StudentsInfo')->where("stid=%d",$stid)->delete()){
                $this->success('删除成功','',IS_AJAX);
            }else{
                $this->error('删除失败','',IS_AJAX);
            }
        }
    }
    //学生信息详情
    public function stdDetail($stid=''){
        $data=M('StudentsInfo')->field("a.*,b.grade_name")->alias("a")->join("sc_class_grade as b on a.cid=b.id")->find();
        $this->assign('data',$data);
        $this->meta_title = '学生信息详情';
        $this->display();
    }
    //学生成绩分析
    public function stdPerformance(){

        $this->display();
    }
    //全市年级成绩统计
    public function  resultStatistics($gid=''){
        $re_list=M('Examine')->field("eid,gid,exam_name")->where("status=%d and gid=%d",[1,$gid])->select();
        $name=M('Grade')->getFieldById($gid,'class_name');
        $prefix   = C('DB_PREFIX');
        $l_table=$prefix.'statistics';
        $r_table=$prefix.'examine';
        $model    = M()->table( $l_table.' a' )->join ( $r_table.' b ON a.eid=b.eid' );
        $_list=$this->lists($model, array('a.status'=>array('egt',0),'a.gid'=>$gid),'a.sid asc','a.*,b.exam_name');
        $this->assign('_list',$_list);
        $this->assign('class_name',$name);
        $this->assign('re_list',$re_list);
        $this->meta_title = '全市年级成绩统计';
        $this->display();
    }
    //全市年级考试成绩统计详情
    public function statisticsDetail($sid='',$gid=''){
        $_list=$this->lists('StatisticsChild',['sid'=>$sid,'status'=>1],'sid asc');
        $name=M('Grade')->getFieldById($gid,'class_name');
        $this->assign('class_name',$name);
        $this->assign('_list',$_list);
        $this->meta_title = '全市年级成绩统计信息详情';
        $this->display();
    }
    //删除全市年级考试统计数据
    public function sdel($sid=''){
        $ob=M('Statistics');
        $ob->startTrans();
        try{
            $ob->where("sid=%d",$sid)->save(['status'=>-1]);
            M('StatisticsChild')->where("sid=%d",$sid)->save(['status'=>-1]);
            $ob->commit();
            $this->success('删除成功!','',IS_AJAX);
        }catch (Exception $e){
            $ob->rollback();
            $this->error('删除失败!','',IS_AJAX);
        }
    }

}





